package com.celebriosoftware.client.fragments;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.GeolocationPermissions;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.celebriosoftware.celebrioclient.R;
import com.celebriosoftware.client.JavaScriptInterface;
import com.celebriosoftware.client.MainActivity;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class AppFragment extends Fragment {
	private MainActivity mainActivity;
	private WebView engine; //webview in which app runs
	private int appId;
	private String appName;
	private String appLabel;
	
	static final int PICK_IMAGE_FOR_GALLERY = 1;
	private ValueCallback<Uri> mUploadMessage;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mainActivity=(MainActivity) this.getActivity();
		appName = (String) getArguments().get("com.celebriosoftware.client.app.url");
		appLabel = (String) getArguments().get("com.celebriosoftware.client.app.label");
		appId = (Integer) getArguments().get("com.celebriosoftware.client.app.id");
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.app, container, false);
		
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		engine = (WebView) getView().findViewById(R.id.web_engine);
		prepareEngine();
 		engine.addJavascriptInterface(new JavaScriptInterface((MainActivity)mainActivity, engine), "Android");
 		//Bug in android, hardware accelerated webview messes transparency
 		engine.loadUrl(appName);
 		engine.setBackgroundColor(0x00000000);		
	}
	
	@Override
	public void onStart() {
		super.onStart();
	}
	
	private void prepareEngine() {
		engine.getSettings().setRenderPriority(RenderPriority.HIGH);
		engine.getSettings().setJavaScriptEnabled(true);
		engine.getSettings().setDatabaseEnabled(true);
		engine.getSettings().setDatabasePath("/data/data/com.celebriosoftware.client/databases"); 
		engine.getSettings().setSupportZoom(false);
		engine.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);
		engine.getSettings().setGeolocationEnabled(true);
		engine.getSettings().setGeolocationDatabasePath(
				"/data/data/com.celebriosoftware.client/databases");
		
		String clientVersion = "unknown";	
		try
		{
			clientVersion = mainActivity.getPackageManager().getPackageInfo(mainActivity.getPackageName(), 0).versionName;
		}
		catch (NameNotFoundException e)
		{
		    Log.e("Celebrio-Version", e.getMessage());
		}
		
		DisplayMetrics metrics = engine.getResources().getDisplayMetrics();
		String userAgent = engine.getSettings().getUserAgentString();
		
		userAgent = userAgent.replaceFirst("(\\))", "; " + mainActivity.CELEBRIO_CLIENT
				+ "/" + clientVersion + "; dpi/" + metrics.densityDpi
				+ "; res-width/" + metrics.widthPixels + "; res-height/"
				+ metrics.heightPixels + ")");
	
		Log.i("Celebrio-UserAgent", userAgent);
		engine.getSettings().setUserAgentString(userAgent);
		engine.setWebViewClient(new WebViewClient() {
			
			@Override
			public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
				if(errorCode==ERROR_HOST_LOOKUP || errorCode==ERROR_CONNECT || errorCode==ERROR_TIMEOUT) {
					mainActivity.lastUri=failingUrl;
					mainActivity.startPeriodicNetworkChecking();
				}
				Log.w("errorCode", ((Integer)errorCode).toString());
				Log.w("errorDescription", description);
				Log.w("errorUrl",  failingUrl);
			};

			@Override
			public void onLoadResource(WebView view, String url) {
				//We download the file
				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD
						&& url.startsWith("http://system.celebriosoftware.com/app/mail/attachment")) {
					DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
					String filename=Uri.parse(url).getQueryParameter("name");
					request.setDescription(mainActivity.getText(R.string.attachment));
					request.setTitle(filename);
				    request.allowScanningByMediaScanner();
				    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
					request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
					
					//Need to give session for authenticated access
					CookieManager cookieManager = CookieManager.getInstance();
	                String cookie = cookieManager.getCookie("http://system.celebriosoftware.com");
	                request.addRequestHeader("Cookie", cookie);
	                
					//Get download service and enqueue file
					DownloadManager manager = (DownloadManager) mainActivity.getSystemService(Context.DOWNLOAD_SERVICE);
					manager.enqueue(request);
			    }
			    else
			    {
			        super.onLoadResource(view, url);
			    } 
			}
			
			@Override
			public void onPageFinished(WebView view, String url) {
				mainActivity.removeLoadingDialog();
				mainActivity.lastUri=url;
				//desktop.postDelayed(refresh, 1000);
				Log.i("page FINISHED", "in app: "+url);
			}

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				mainActivity.showLoadingDialog(appLabel, MainActivity.appsIcons.get(appId));
				Log.i("page STARTED", "in app: "+url);
			}
		});
		
		engine.setWebChromeClient(new MyWebChromeClient());
	}
	
	private Runnable refresh = new Runnable() {
        public void run() {
			//desktop.postInvalidate();
        }
    };
	
	class MyWebChromeClient extends WebChromeClient {
		@Override
		public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
			callback.invoke(origin, true, false);
		}
		
		// The undocumented magic method override
	    // Eclipse will swear at you if you try to put @Override here
		// This gets run by browser when user clicks on input file button
	    public void openFileChooser(ValueCallback<Uri> uploadMsg) {
	        mUploadMessage = uploadMsg;
			Intent pickImageIntent = new Intent(Intent.ACTION_GET_CONTENT);
			pickImageIntent.setType("image/*");
			startActivityForResult(pickImageIntent,PICK_IMAGE_FOR_GALLERY);

			pickImageIntent.addCategory(Intent.CATEGORY_OPENABLE);
			startActivityForResult(Intent.createChooser( pickImageIntent, "File Chooser" ),PICK_IMAGE_FOR_GALLERY);	
	    }
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            openFileChooser(uploadMsg);
        }                  
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            openFileChooser(uploadMsg);
        }
	}
	
	//alternative image uploading way, not used now
	public void loadFileIntoGallery() {
		//Intent pickImageIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		//startActivityForResult(pickImageIntent,PICK_IMAGE_FOR_GALLERY);
		Intent pickImageIntent = new Intent(Intent.ACTION_GET_CONTENT);
		pickImageIntent.setType("image/*");
		startActivityForResult(pickImageIntent,PICK_IMAGE_FOR_GALLERY);
		//pickImageIntent.addCategory(Intent.CATEGORY_OPENABLE);
		//pickImageIntent.setAction(Intent.ACTION_GET_CONTENT);
		//pickImageIntent.addCategory(Intent.CATEGORY_OPENABLE);
		//startActivityForResult(Intent.createChooser( pickImageIntent, "File Chooser" ),PICK_IMAGE_FOR_GALLERY);	
	}
	
	//Run when user selects a file to upload
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == PICK_IMAGE_FOR_GALLERY) {
            if (resultCode == Activity.RESULT_OK) {
            	Uri imageUri = data.getData();
            	mUploadMessage.onReceiveValue(imageUri);
            	return;
            	//alternative way - sending image by url
            	//InputStream imageStream = getContentResolver().openInputStream(imageUri);
                //Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
            	//String base64String = Base64.encodeToString(yourSelectedImage, Base64.URL_SAFE);
            	//String base64String = Base64.encodeBase64String({my byte[]});
            	//<img src="data:image/jpeg;base64,{base64String from above}"/>
            }
            mUploadMessage.onReceiveValue(null); //otherwise it freezes on unsuccessful pick
        }
        //super.onActivityResult(requestCode, resultCode, data);
    }
}


